import qs from 'qs';
import { mapActions, mapGetters } from 'vuex';

const mixin = {
  data() {
    return {
      query: {},
      userInfo: {},
    };
  },
  created() {
    this.initQuery();
    this.getUserInfo();
  },
  computed: {
    ...mapGetters(['$userInfo']),
  },
  methods: {
    initQuery() {
      const query = window.location.href.split('?')[1];
      if (query) {
        this.query = qs.parse(query);
      }
    },
    async getUserInfo() {
      if (!this.$userInfo.nickname) {
        try {
          const res = await this.$appService.userInfo({ refresh: true });
          this.$setUserInfo(res);
          if (res.token) {
            window.localStorage.setItem('token', res.token);
          }
        } catch (err) {
          if (this.needLogin) {
            this.login();
          }
        }
      }
    },
    login() {
      this.$appService
        .login()
        .then((res) => {
          this.userInfo = res;
          this.$setUserInfo(res);
        })
        .catch((err) => {});
    },
    hideWXShare() {
      function onBridgeReady() {
        WeixinJSBridge.call('hideOptionMenu'); //隐藏微信下的分享菜单
      }
      if (typeof WeixinJSBridge == 'undefined') {
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
          document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        }
      } else {
        onBridgeReady();
      }
    },
    ...mapActions(['$setUserInfo']),
  },
};
export default mixin;
